#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import datetime
import os
try:
	import mechanize
except:
	print "'python-mechanize is not installed. Exiting."
	exit()
config_path = os.path.expanduser('~/.config/backup-google-cal')
config_file = 'config'
sys.path.append(config_path)
try:
	config = __import__(config_file)
	backupdir = os.path.expanduser(config.export_path)
	if not os.path.exists(backupdir):
	    os.makedirs(backupdir)
except:
#	import traceback
#	traceback.print_exc()
	cfg_file_text = """#This is the config file for backup-google-cal.
# -*- coding: utf-8 -*-
email = 'some-name@gmail.com'
pwd = 'secrets'
export_path = '~/backup/'"""

	cfg_file = "%s.py" % os.path.join(config_path,config_file)
	print "The config file '%s' could not be read" % cfg_file
	try:
		os.makedirs(config_path)
	except:
		pass
	f = open(cfg_file,'w')
	f.write(cfg_file_text)
	f.close()
	try:
		import gio
		apps = gio.app_info_get_all_for_type("text/plain")
		editor = apps[0]
		editor.launch_uris(['file://'+cfg_file])
	except:
		print "Opening the file with" % os.path.join(config_path,config_file)
		print cfg_file_text
	exit()

print "Backing up calendars of '%s':" % config.email

br=mechanize.Browser()
br.open('https://www.google.com/calendar/exporticalzip')
br.select_form(nr=0)
br['Email']=config.email
br['Passwd']=config.pwd
br.submit()
br.retrieve('https://www.google.com/calendar/exporticalzip',os.path.join(backupdir,'ical-export-%s.zip' % datetime.datetime.now()))
